/*
 * common_thread.h
 *
 *  Created on: 2011-4-17
 *      Author: chenl
 */

#ifndef COMMON_THREAD_H_
#define COMMON_THREAD_H_

#include "common_type.h"
#include "common_err.h"
#include "common_delay.h"
#include "common_libnamespace.h"

#include <stdio.h>
#include <pthread.h>

CHENLIB_NAMESPACE_BEGIN

enum
{
	enmDefaultThreadExecutePeriod = 1000,
};

class CThread
{
public:
	CThread() : thread_(0), bTerminated_(false){}
	virtual ~CThread(){}

public:
	int32_t Start()
	{
		bTerminated_ = false;
		pthread_create(&thread_, NULL, CThread::ThreadProc, this);
		return S_OK;
	}
	virtual void Execute()
	{
		uint32_t n = 0;
		while (!bTerminated_)
		{
			if (0 == (++n) % 1000)
			{
				printf("exp thread exec %d\n", n);
			}
			DELAY(1000);
		}
		pthread_exit(NULL);
	}
	virtual int32_t Terminate()
	{
		if (bTerminated_)
		{
			return S_OK;
		}
		bTerminated_ = true;
		if (0 != thread_)
		{
			pthread_join(thread_, NULL);
		}
		return S_OK;
	}

	bool IsTerminated() const
	{
		return bTerminated_;
	}

protected:
	static void* ThreadProc(void *pParam)
	{
		if (NULL == pParam)
		{
			return NULL;
		}
		CThread* p = (CThread*) pParam;
		p->Execute();
		return NULL;
	}

protected:
	pthread_t 		thread_;
//	pthread_mutex_t	thread_mutex;
	bool 			bTerminated_;
};

CHENLIB_NAMESPACE_END

#endif /* COMMON_THREAD_H_ */
